package com.ybkj.daijia.api.driver.v3;

import com.alibaba.fastjson.JSONObject;
import com.ybkj.daijia.serverUtils.QRCodeUtil;
import com.ybkj.daijia.Setting;
import com.ybkj.daijia.serverUtils.SettingUtils;
import com.ybkj.daijia.api.data.PushDriver;
import com.ybkj.daijia.api.driver.ErrorConstant;
import com.ybkj.daijia.api.driver.SecurityUtils;
import com.ybkj.daijia.api.driver.transport.ChartTransport;
import com.ybkj.daijia.api.driver.transport.ResultTransport;
import com.ybkj.daijia.common.RandomString;
import com.ybkj.daijia.common.Result;
import com.ybkj.daijia.page.Page;
import com.ybkj.daijia.page.Pageable;
import com.ybkj.daijia.page.impl.PageImpl;
import com.ybkj.daijia.page.impl.PageRequest;
import com.ybkj.daijia.server.event.model.ActivityCheckEvent;
import com.ybkj.daijia.server.event.model.DriverUpdateLocationEvent;
import com.ybkj.daijia.server.event.model.MemberRebateEvent;
import com.ybkj.daijia.server.event.model.OrderFinishEvent;
import com.ybkj.daijia.server.mc.Enterprise;
import com.ybkj.daijia.server.mc.Passenger;
import com.ybkj.daijia.server.model.Area;
import com.ybkj.daijia.server.model.ChargeStartTime;
import com.ybkj.daijia.server.model.Company;
import com.ybkj.daijia.server.model.Driver;
import com.ybkj.daijia.server.model.DriverPaymentsRecord;
import com.ybkj.daijia.server.model.DriverRebate;
import com.ybkj.daijia.server.model.MemberRebate;
import com.ybkj.daijia.server.model.Order;
import com.ybkj.daijia.server.model.Order.PayType;
import com.ybkj.daijia.server.model.Order.PayTypeDetails;
import com.ybkj.daijia.server.model.OrderGroup;
import com.ybkj.daijia.server.model.PhoneSmsRecord;
import com.ybkj.daijia.server.model.SmsTemplet;
import com.ybkj.daijia.server.model.SmsTemplet.SmsType;
import com.ybkj.daijia.server.reactor.ReactorVo;
import com.ybkj.daijia.server.sales.Activity.ActivityEvent;
import com.ybkj.daijia.server.sales.Coupon;
import com.ybkj.daijia.server.service.ActivityService;
import com.ybkj.daijia.server.service.AppVersionService;
import com.ybkj.daijia.server.service.AreaService;
import com.ybkj.daijia.server.service.CarTypeService;
import com.ybkj.daijia.server.service.CompanyService;
import com.ybkj.daijia.server.service.CouponRuleService;
import com.ybkj.daijia.server.service.CouponService;
import com.ybkj.daijia.server.service.DriverApplyService;
import com.ybkj.daijia.server.service.DriverPaymentsRecordService;
import com.ybkj.daijia.server.service.DriverRebateService;
import com.ybkj.daijia.server.service.DriverRechargeRecordService;
import com.ybkj.daijia.server.service.DriverService;
import com.ybkj.daijia.server.service.ErrandService;
import com.ybkj.daijia.server.service.FinancialRecordService;
import com.ybkj.daijia.server.service.FreightService;
import com.ybkj.daijia.server.service.MemberAccountService;
import com.ybkj.daijia.server.service.MemberService;
import com.ybkj.daijia.server.service.OrderGroupService;
import com.ybkj.daijia.server.service.OrderService;
import com.ybkj.daijia.server.service.OrderStatusService;
import com.ybkj.daijia.server.service.PhoneSmsRecordService;
import com.ybkj.daijia.server.service.SmsService;
import com.ybkj.daijia.server.service.ZhuancheService;
import com.ybkj.daijia.server.service.impl.DefaultDriverRebateService;
import java.io.File;
import java.io.FileNotFoundException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.ApplicationEventMulticaster;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.WebUtils;

/**
 * @author bo
 */
@Controller("driverProcessV3Controller")
@RequestMapping(value = "driver/api/rest/v3")
public class ProcessController {

    private static final Logger logger = LoggerFactory.getLogger(ProcessController.class);

    @Autowired
    private DriverService driverService;

    @Autowired
    private DriverRebateService driverRebateService;

    @Autowired
    private PhoneSmsRecordService phoneSmsRecordService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderGroupService orderGroupService;

    @Autowired
    private OrderStatusService orderStatusService;

    @Autowired
    private MemberAccountService memberAccountService;

    @Autowired
    private MemberService memberService;

    @Autowired
    private FinancialRecordService financialRecordService;

    @Autowired
    private DriverApplyService driverApplyService;

    @Autowired
    private CouponService couponService;

    @Autowired
    private CouponRuleService couponRuleService;

    @Autowired
    private ActivityService activityService;

    @Autowired
    private SettingUtils settingUtils;

    @Autowired
    private ApplicationEventMulticaster applicationEventMulticaster;

    @Autowired
    private CompanyService companyService;

    @Autowired
    private AreaService areaService;

    @Autowired
    private AppVersionService appVersionService;

    @Autowired
    private DriverRechargeRecordService driverRechargeRecordService;

    @Autowired
    private ZhuancheService zhuancheService;

    @Autowired
    private FreightService freightService;

    @Autowired
    private CarTypeService carTypeService;

    @Autowired
    private DriverPaymentsRecordService driverPaymentsRecordService;

    @Autowired
    private SmsService smsService;

    @Autowired
    private ErrandService errandService;
    @Autowired
    private DefaultDriverRebateService defaultDriverRebateService;

    /**
     * 服务人员获取附近服务人员
     *
     * @param longitude 经度
     * @param latitude  纬度
     * @param appKey
     * @param token     token令牌
     * @param timestamp 时间戳
     * @return
     */
    @RequestMapping(value = "queryNearDrivers", method = RequestMethod.POST)
    public @ResponseBody
    ResultTransport queryNearDrivers(Long driverId, Double longitude, Double latitude,
        String appKey, String token, String timestamp) {

        logger.debug("recv driverId:{},longitude:{},latitude:{},appKey:{},token:{},timestamp:{}",
            longitude, latitude, appKey, token, timestamp);

        if (null == driverId || null == longitude || null == latitude || SecurityUtils
            .isBlank(appKey, token, timestamp)) {
            return ResultTransport.getErrorBy(ErrorConstant.PARAM_ERROR);
        }

        List<String> params = new LinkedList<String>();
        params.add(String.valueOf(driverId));
        params.add(String.valueOf(longitude));
        params.add(String.valueOf(latitude));
        params.add(timestamp);
        params.add(appKey);

        if (!SecurityUtils.checkToken(params, token)) {
            return ResultTransport.getErrorBy(ErrorConstant.TOKEN_ERROR);
        }

        try {
            Setting setting = settingUtils.get();

            List<Driver> drivers = driverService.queryNearDrivers2(driverId, longitude, latitude);

            List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
            if (org.apache.commons.collections.CollectionUtils.isNotEmpty(drivers)) {
                for (Driver driver : drivers) {
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("driverId", driver.getId());
                    map.put("driverName", driver.getName());
                    map.put("driverHead",
                        setting.getWebUrl() + "/upload/driver/" + driver.getPhoto());
                    map.put("driverDistance", driver.getDistanceStr());
                    map.put("driverMeter", driver.getDistance() * 1000);
                    if (driver.getStatus().equals(Driver.DRIVER_ONLINE)) {
                        map.put("driverStatus", 0);
                    } else {
                        map.put("driverStatus", 1);
                    }
                    map.put("driverLng", driver.getLongitude());
                    map.put("driverLat", driver.getLatitude());
                    map.put("workCar", driver.isWorkCar());
                    mapList.add(map);
                }
            }

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstant.SUCCESS);
            instance.setData(mapList);

            return instance;

        } catch (Exception e) {
            logger.error("api v3 queryNearDrivers error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstant.SERVER_ERROR);
        }

    }

    @RequestMapping(value = "indexData", method = RequestMethod.POST)
    public @ResponseBody
    ResultTransport indexData(
        Long driverId, Double longitude, Double latitude, String address,
        String appKey, String token, String timestamp) {

        logger.debug(
            "recv driverId:{},longitude:{},latitude:{},address:{},appKey:{},token:{},timestamp:{}",
            driverId, longitude, latitude, address, appKey, token, timestamp);

        if (null == driverId || SecurityUtils.isBlank(appKey, token, timestamp)) {
            return ResultTransport.getErrorBy(ErrorConstant.PARAM_ERROR);
        }

        if (!StringUtils.isNumeric(timestamp) || !SecurityUtils
            .checkTimestamp(Long.parseLong(timestamp))) {
            return ResultTransport.getErrorBy(ErrorConstant.TIMESTAMP_ERROR);
        }

        List<String> params = new LinkedList<String>();
        params.add(String.valueOf(driverId));
        if (null != longitude) {
            params.add(String.valueOf(longitude));
        }
        if (null != latitude) {
            params.add(String.valueOf(latitude));
        }
        if (StringUtils.isNotBlank(address)) {
            params.add(String.valueOf(address));
        }
        params.add(timestamp);
        params.add(appKey);

        if (!SecurityUtils.checkToken(params, token)) {
            return ResultTransport.getErrorBy(ErrorConstant.TOKEN_ERROR);
        }

        Driver driver = driverService.findOne(driverId);

        if (null == driver) {
            return ResultTransport.getErrorBy(ErrorConstant.DRIVER_NOT_EXISTS);
        }

        try {

            if (null != longitude && null != latitude && StringUtils.isNotBlank(address)) {
                if (latitude > 3 && latitude < 54 && longitude > 73 && longitude < 136) {
                    driverService.updateLocation(longitude, latitude, longitude, latitude, address,
                        driver.getId());
                    //发送位置变更推送
                    DriverUpdateLocationEvent updateLocationEvent = new DriverUpdateLocationEvent(
                        driver, latitude, longitude, address);
                    applicationEventMulticaster.multicastEvent(updateLocationEvent);
                }
            }

            Map<String, Object> dataMap = new HashMap<String, Object>();

            //服务人员信息
            Company company = companyService.findOne(driver.getCompanyId());

            PushDriver pushDriver = new PushDriver();

            pushDriver.setCompanyId(company.getId());
            pushDriver.setCompanyName(company.getAbbreviation());
            pushDriver.setGender(driver.getGender());
            pushDriver.setId(driver.getId());
            pushDriver.setIsFreeze(driver.getIsFreeze());
            pushDriver.setName(driver.getName());
            pushDriver.setPhone(driver.getPhone());
            pushDriver.setPhoto(driver.getPhoto());
            pushDriver.setLatitude(driver.getLastLatitude());
            pushDriver.setLongitude(driver.getLongitude());
            pushDriver.setStatus(driver.getStatus());
            pushDriver.setType(driver.getType());
            pushDriver.setUsername(driver.getUsername());
            pushDriver.setVirtual(driver.getVirtual());
            pushDriver.setWorkCar(driver.isWorkCar());
            pushDriver.setDriverJobType(driver.getDriverJobType());
            dataMap.put("driver", pushDriver);

            //新工单
            List<Order> newOrders = orderService
                .findByDriverAndStatus(driver, Order.ORDER_STATUS_YIPAIDAN);
            if (CollectionUtils.isNotEmpty(newOrders)) {
                for (Order order : newOrders) {
                    Company thisCompany = companyService.findOne(order.getCompanyId());
                    if (null != thisCompany) {
                        Passenger passenger = memberService
                            .findOnePassengerByPhone(order.getClientPhone());
                        if (null != passenger) {
                            Area daijiaArea = null;
                            if (passenger.getType().equals(Passenger.TYPE_PASSENGER)) {
                                daijiaArea = areaService.findDaijiaByPassenger(passenger.getId());
                            } else if (passenger.getType().equals(Passenger.TYPE_ENTERPRISE)) {
                                daijiaArea = areaService
                                    .findDaijiaByEnterprise(passenger.getEnterprise_id());
                            }

                            if (null != daijiaArea) {
                                thisCompany
                                    .setArea(areaService.findOneWithCharge(daijiaArea.getId()));
                            } else {
                                thisCompany.setArea(
                                    areaService.findOneWithCharge(thisCompany.getAreaId()));
                            }
                        } else {
                            thisCompany
                                .setArea(areaService.findOneWithCharge(thisCompany.getAreaId()));
                        }
                    }
                    order.setCompany(thisCompany);
                    //订单分组
                    if (null != order.getOrderGroupId()) {
                        OrderGroup orderGroup = orderGroupService.findOne(order.getOrderGroupId());
                        if (null != orderGroup && null != orderGroup.getDriverId() && !orderGroup
                            .getDriverId().equals(order.getDriverId())) {
                            Driver jiedanDriver = driverService.findOne(orderGroup.getDriverId());
                            order.setClientPhone(jiedanDriver.getPhone());
                            order.setUserPhone(jiedanDriver.getPhone());
                        }
                    }
                }
            }
            dataMap.put("newTasks", newOrders);
            //----专车----
            List<com.ybkj.daijia.server.zhuan.Order> newOrders_zhuan = new ArrayList<com.ybkj.daijia.server.zhuan.Order>();

            newOrders_zhuan = zhuancheService.queryByEmployId(driverId, "pai");
            dataMap.put("newTasks_zhuan", newOrders_zhuan);//新派过来的专车订单
            List<com.ybkj.daijia.server.zhuan.Order> excuteTasks_zhuan = new ArrayList<com.ybkj.daijia.server.zhuan.Order>();
            excuteTasks_zhuan = zhuancheService.queryByEmployId(driverId, "waitorrun");
            dataMap.put("excuteTasks_zhuan", excuteTasks_zhuan);//执行中的专车订单

            List<com.ybkj.daijia.server.zhuan.Order> finishTasks_zhuan = new ArrayList<com.ybkj.daijia.server.zhuan.Order>();
            finishTasks_zhuan = zhuancheService.queryByEmployId(driverId, "finish");

            dataMap.put("finishTasks_zhuan", finishTasks_zhuan);//完成的专车订单
            //----专车----

            //----货运订单----
            List<com.ybkj.daijia.server.freight.Order> newOrders_freight = new ArrayList<com.ybkj.daijia.server.freight.Order>();

            newOrders_freight = freightService.queryByEmployId(driverId, "pai");
            dataMap.put("newTasks_freight", newOrders_freight);//新派过来的货运订单
            List<com.ybkj.daijia.server.freight.Order> excuteTasks_freight = new ArrayList<com.ybkj.daijia.server.freight.Order>();
            excuteTasks_freight = freightService.queryByEmployId(driverId, "waitorrun");
            dataMap.put("excuteTasks_freight", excuteTasks_freight);//执行中的专车订单

            List<com.ybkj.daijia.server.freight.Order> finishTasks_freight = new ArrayList<com.ybkj.daijia.server.freight.Order>();
            finishTasks_freight = freightService.queryByEmployId(driverId, "finish");

            dataMap.put("finishTasks_freight", finishTasks_freight);//完成的专车订单
            //----货运订单----

            //----跑腿订单----
            List<Map<String, Object>> newOrders_errand = errandService
                .queryByEmployId(driverId, "pai", latitude, longitude);
            dataMap.put("newTasks_errand", newOrders_errand);//新派过来的跑腿订单
            List<Map<String, Object>> excuteTasks_errand = errandService
                .queryByEmployId(driverId, "waitorrun", latitude, longitude);
            dataMap.put("excuteTasks_errand", excuteTasks_errand);//执行中的跑腿订单
            //----跑腿订单----

            //执行中工单
            List<Order> busyOrders = orderService
                .findByDriverAndStatus(driver, Order.ORDER_STATUS_BUSY);
            if (CollectionUtils.isNotEmpty(busyOrders)) {
                for (Order order : busyOrders) {
                    Company thisCompany = companyService.findOne(order.getCompanyId());
                    if (null != thisCompany) {
                        Passenger passenger = memberService
                            .findOnePassengerByPhone(order.getClientPhone());
                        if (null != passenger) {
                            Area daijiaArea = null;
                            if (passenger.getType().equals(Passenger.TYPE_PASSENGER)) {
                                daijiaArea = areaService.findDaijiaByPassenger(passenger.getId());
                            } else if (passenger.getType().equals(Passenger.TYPE_ENTERPRISE)) {
                                daijiaArea = areaService
                                    .findDaijiaByEnterprise(passenger.getEnterprise_id());
                            }

                            if (null != daijiaArea) {
                                thisCompany
                                    .setArea(areaService.findOneWithCharge(daijiaArea.getId()));
                            } else {
                                thisCompany.setArea(
                                    areaService.findOneWithCharge(thisCompany.getAreaId()));
                            }
                        } else {
                            thisCompany
                                .setArea(areaService.findOneWithCharge(thisCompany.getAreaId()));
                        }
                    }
                    order.setCompany(thisCompany);
                    //订单分组
                    if (null != order.getOrderGroupId()) {
                        OrderGroup orderGroup = orderGroupService.findOne(order.getOrderGroupId());
                        if (null != orderGroup && null != orderGroup.getDriverId() && !orderGroup
                            .getDriverId().equals(order.getDriverId())) {
                            Driver jiedanDriver = driverService.findOne(orderGroup.getDriverId());
                            order.setClientPhone(jiedanDriver.getPhone());
                            order.setUserPhone(jiedanDriver.getPhone());
                        }
                    }
                }
            }
            dataMap.put("excuteTasks", busyOrders);

            //完成未报单工单
            List<Order> finishedOrders = orderService
                .findByDriverAndStatus(driver, Order.ORDER_STATUS_FINISHED);
            if (CollectionUtils.isNotEmpty(finishedOrders)) {
                for (Order order : finishedOrders) {
                    Company thisCompany = companyService.findOne(order.getCompanyId());
                    if (null != thisCompany) {
                        Passenger passenger = memberService
                            .findOnePassengerByPhone(order.getClientPhone());
                        if (null != passenger) {
                            Area daijiaArea = null;
                            if (passenger.getType().equals(Passenger.TYPE_PASSENGER)) {
                                daijiaArea = areaService.findDaijiaByPassenger(passenger.getId());
                            } else if (passenger.getType().equals(Passenger.TYPE_ENTERPRISE)) {
                                daijiaArea = areaService
                                    .findDaijiaByEnterprise(passenger.getEnterprise_id());
                            }

                            if (null != daijiaArea) {
                                thisCompany
                                    .setArea(areaService.findOneWithCharge(daijiaArea.getId()));
                            } else {
                                thisCompany.setArea(
                                    areaService.findOneWithCharge(thisCompany.getAreaId()));
                            }
                        } else {
                            thisCompany
                                .setArea(areaService.findOneWithCharge(thisCompany.getAreaId()));
                        }
                    }
                    order.setCompany(thisCompany);
                    //订单分组
                    if (null != order.getOrderGroupId()) {
                        OrderGroup orderGroup = orderGroupService.findOne(order.getOrderGroupId());
                        if (null != orderGroup && null != orderGroup.getDriverId() && !orderGroup
                            .getDriverId().equals(order.getDriverId())) {
                            Driver jiedanDriver = driverService.findOne(orderGroup.getDriverId());
                            order.setClientPhone(jiedanDriver.getPhone());
                            order.setUserPhone(jiedanDriver.getPhone());
                        }
                    }
                }
            }
            dataMap.put("finishTasks", finishedOrders);

            //APP配置
            Map<String, Object> settingMap = new HashMap<String, Object>();
            Setting setting = settingUtils.get();
            settingMap.put("allowRushOrder", setting.isAllowRushOrder());
            settingMap.put("allowWorkCar", setting.isAllowWorkCar());
            settingMap.put("allowWorkCarZhuandan", setting.isAllowWorkCarZhuandan());
            settingMap.put("allowDriverZhuandan", setting.isAllowDriverZhuandan());
            settingMap.put("allowDriverCancel", setting.isAllowDriverCancel());
            settingMap.put("mustToPlace", setting.isMustToPlace());
            settingMap.put("mustMemberInfo", setting.isMustMemberInfo());
            settingMap.put("errandFixPrice", setting.isPaotuiFixPrice());
            settingMap.put("errandValuationMethod", setting.getErrandValuationMethod());
            dataMap.put("setting", settingMap);

            //统计
            Calendar nowCalendar = Calendar.getInstance();
            int nowHour = nowCalendar.get(Calendar.HOUR_OF_DAY);

            //查询今日订单
            Calendar calendaer = Calendar.getInstance();
            calendaer.set(Calendar.HOUR_OF_DAY, setting.getWorkBegin());
            calendaer.set(Calendar.MINUTE, 0);
            calendaer.set(Calendar.SECOND, 0);
            Date end = calendaer.getTime();
            Date begin = DateUtils.addHours(end, -24);
            if (setting.getWorkBegin() < nowHour) {
                end = DateUtils.addHours(end, 24);
                begin = DateUtils.addHours(begin, 24);
            }
            //计算单量与总价
            ChartTransport chartTran = new ChartTransport();
            long todayTasks = orderService.counByDriverAndFinishTime(driverId, begin, end);
            double todayIncome = orderService.sumByDriverAndFinishTime(driverId, begin, end);
            chartTran.setTodayTasks(todayTasks);
            chartTran.setTodayIncome(todayIncome);

            //查询昨日订单
            begin = DateUtils.addHours(begin, -24);
            end = DateUtils.addHours(end, -24);
            long yesterdayTasks = orderService.counByDriverAndFinishTime(driverId, begin, end);
            double yesterdayIncome = orderService.sumByDriverAndFinishTime(driverId, begin, end);

            chartTran.setYesterdayTasks(yesterdayTasks);
            chartTran.setYesterdayIncome(yesterdayIncome);

            //查询本月
            calendaer = Calendar.getInstance();
            calendaer.set(Calendar.DAY_OF_MONTH, calendaer.getActualMinimum(Calendar.DAY_OF_MONTH));
            calendaer.set(Calendar.HOUR_OF_DAY, setting.getWorkBegin());
            calendaer.set(Calendar.MINUTE, 0);
            calendaer.set(Calendar.MILLISECOND, 0);
            begin = calendaer.getTime();

            calendaer.set(Calendar.DAY_OF_MONTH, calendaer.getActualMaximum(Calendar.DAY_OF_MONTH));
            calendaer.set(Calendar.HOUR_OF_DAY, setting.getWorkBegin());
            calendaer.set(Calendar.MINUTE, 0);
            calendaer.set(Calendar.MILLISECOND, 0);
            end = calendaer.getTime();
            end = DateUtils.addDays(end, 24);

            long thisMonthTasks = orderService.counByDriverAndFinishTime(driverId, begin, end);
            double thisMonthIncome = orderService.sumByDriverAndFinishTime(driverId, begin, end);

            chartTran.setThisMonthTasks(thisMonthTasks);
            chartTran.setThisMonthIncome(thisMonthIncome);

            dataMap.put("statistics", chartTran);

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstant.SUCCESS);
            instance.setVer("3");
            instance.setData(dataMap);
            return instance;

        } catch (Exception e) {
            logger.error("api v3 driver indexData error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstant.SERVER_ERROR);
        }

    }

    @RequestMapping(value = "completeTask", method = RequestMethod.GET)
    public String completeTask() {
        return "driverapp/completetask";
    }

    @RequestMapping(value = "completeTask", method = RequestMethod.POST)
    public @ResponseBody
    ResultTransport completeTask(
        Long driverId, Long orderId,
        Double shouldCash, Double mileage, BigDecimal mileageMoney,
        Integer waitedTime, BigDecimal waitedMoney,
        Long waitStartTime, Long travelBeginTime,
        String appKey, String token, String timestamp) {

        logger.debug(
            "recv driverId:{},orderId:{},shouldCash:{},mileage:{},mileageMoney:{},waitedTime:{},waitedMoney:{},waitStartTime:{},travelBeginTime:{},appKey:{},token:{},timestamp:{}",
            driverId, orderId, shouldCash, mileage, mileageMoney, waitedTime, waitedMoney,
            waitStartTime, travelBeginTime, appKey, token, timestamp);

        if (null == driverId || null == orderId || null == shouldCash
            || null == mileage | null == mileageMoney ||
            null == waitedTime || null == waitedMoney || null == waitStartTime
            || null == travelBeginTime ||
            SecurityUtils.isBlank(appKey, token, timestamp)) {

            return ResultTransport.getErrorBy(ErrorConstant.PARAM_ERROR);

        }

        if (!StringUtils.isNumeric(timestamp) || !SecurityUtils
            .checkTimestamp(Long.parseLong(timestamp))) {
            return ResultTransport.getErrorBy(ErrorConstant.TIMESTAMP_ERROR);
        }

        List<String> params = new LinkedList<String>();
        params.add(String.valueOf(driverId));
        params.add(String.valueOf(orderId));
        params.add(String.valueOf(shouldCash));
        params.add(String.valueOf(mileage));
        params.add(String.valueOf(mileageMoney));
        params.add(String.valueOf(waitedTime));
        params.add(String.valueOf(waitedMoney));
        params.add(String.valueOf(waitStartTime));
        params.add(String.valueOf(travelBeginTime));
        params.add(timestamp);
        params.add(appKey);

        if (!SecurityUtils.checkToken(params, token)) {
            return ResultTransport.getErrorBy(ErrorConstant.TOKEN_ERROR);
        }

        try {

            Driver driver = driverService.findOne(driverId);

            if (null == driver) {
                return ResultTransport.getErrorBy(ErrorConstant.DRIVER_NOT_EXISTS);
            }

            Order order = orderService.findOne(orderId);
            if (null == order) {
                return ResultTransport.getErrorBy(ErrorConstant.ORDER_NOT_EXISTS_ERROR);
            }

            if (!order.getStatus().equals(Order.ORDER_STATUS_BUSY)) {
                return ResultTransport.getErrorBy(ErrorConstant.ORDER_STATUS_ERROR);
            }

            if (!order.getDriverId().equals(driverId)) {
                return ResultTransport.getErrorBy(ErrorConstant.ORDER_DRIVER_OWNER_ERROR);
            }

            Passenger passenger = memberService.findOnePassengerByPhone(order.getClientPhone());

//			if(null==memberAccount){
//				return ResultTransport.getErrorBy(ErrorConstant.MEMBER_NOT_EXISTS);
//			}

            order.setOrderStatuss(orderStatusService.findByOrder(order.getId()));

            Map<String, Object> map = new HashMap<String, Object>();

            order.setShouldCash(new BigDecimal(shouldCash).setScale(1, BigDecimal.ROUND_HALF_UP));

            BigDecimal m = new BigDecimal(mileage);
            double df = m.setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue();
            order.setMileage(df);

            order.setWaitedTime(waitedTime);

            List<Coupon> coupons = couponService
                .listByPassenger(order.getClientId(), null, null, null);
            BigDecimal couponMoney = BigDecimal.ZERO;
            if (CollectionUtils.isNotEmpty(coupons)) {
                for (Coupon coupon : coupons) {
                    coupon.setCouponRule(couponRuleService.findOne(coupon.getCouponRuleId()));
                    couponMoney = couponMoney.add(coupon.getCouponRule().getMoney());
                }
            }

            Company company = companyService.findOne(order.getCompanyId());

            map.put("orderId", order.getId());
            map.put("orderNumber", order.getOrderNumber());
            map.put("orderType", order.getOrderType());
            map.put("orderCompanyName", company.getAbbreviation());

            map.put("memberPhone", order.getClientPhone());
            map.put("memberName", order.getClientName());

            if (null != passenger) {
                map.put("memberType", passenger.getTypeStr());

                if (passenger.getType() == Passenger.TYPE_PASSENGER) {
                    map.put("memberCompanyName", "");
                    map.put("isOverdraw", passenger.isAllowOverdraw());
                    map.put("virtual", passenger.getDrawMoney());
                } else if (passenger.getType() == Passenger.TYPE_ENTERPRISE) {
                    Enterprise enterprise = memberService
                        .findOneEnterprise(passenger.getEnterprise_id());
                    map.put("memberCompanyName", enterprise.getName());
                    map.put("isOverdraw", enterprise.isAllowOverdraw());
                    map.put("virtual", enterprise.getDrawMoney());
                }

//				map.put("memberEcp", memberAccount.getMemberEcp());
//				map.put("memberEcn", memberAccount.getMemberEcn());
                map.put("memberCarNumber", passenger.getPlateNumber());
            } else {
                map.put("memberCompanyName", "");
                map.put("isOverdraw", false);
                map.put("virtual", 0);

                map.put("memberEcp", "");
                map.put("memberEcn", "");
                map.put("memberCarNumber", "");
            }

            map.put("couponMoney", couponMoney);
            map.put("coupons", coupons);
            map.put("couponId", order.getCouponId());

            //代驾时间、钱
            Date startDriveDate = order.getDaijiaTime2();//开始代驾时间
            ChargeStartTime currChargeStartTime = null;
            if (null != startDriveDate) {

                Company company2 = companyService.findOne(order.getCompanyId());

                Area area = null;
                if (null != passenger) {
                    Area areaDaijia = areaService.findDaijiaByPassenger(passenger.getId());
                    if (null != areaDaijia) {
                        area = areaService.findOneWithCharge(areaDaijia.getId());
                    }
                } else {
                    area = areaService.findOneWithCharge(company2.getAreaId());
                }

                if (null != area) {
                    List<ChargeStartTime> chargeStartTimes = area.getChargeStartTimes();

                    if (!CollectionUtils.isEmpty(chargeStartTimes)) {
                        Calendar calendar = Calendar.getInstance();
                        calendar.setTime(startDriveDate);
                        int hour = calendar.get(Calendar.HOUR_OF_DAY);
                        int minute = calendar.get(Calendar.MINUTE);
                        int hourminute = (hour * 60) + minute;
                        for (ChargeStartTime cst : chargeStartTimes) {
                            if (hourminute >= (cst.getStartHour() * 60) + cst.getStartMinute()
                                && hourminute <= (cst.getEndHour() * 60) + cst.getEndMinute()) {
                                currChargeStartTime = cst;
                            }
                        }
                    }
                }

            }

            if (null != startDriveDate) {
                SimpleDateFormat formatter = new SimpleDateFormat("MM-dd HH:mm");
                map.put("startDriveDate", formatter.format(startDriveDate));
            }

            if (order.isFixPrice()) {//定价
                map.put("qibuMoney", BigDecimal.ZERO);
                map.put("mileageMoney", BigDecimal.ZERO);
                map.put("waitedMoney", BigDecimal.ZERO);
            } else {
                if (null != currChargeStartTime) {
                    map.put("qibuMoney", currChargeStartTime.getCost());
                } else {
                    map.put("qibuMoney", BigDecimal.ZERO);
                }
                map.put("mileageMoney", mileageMoney);
                map.put("waitedMoney", waitedMoney);
            }

            //form data
            map.put("driverId", driverId);
            map.put("shouldCash", shouldCash);
            map.put("mileage", df);
            map.put("waitedTime", waitedTime);
            map.put("waitStartTime", waitStartTime);
            map.put("travelBeginTime", travelBeginTime);

            //setting
            Setting setting = settingUtils.get();
            map.put("mustMemberInfo", setting.isMustMemberInfo());
            map.put("allowModifyCash", setting.isAllowModifyCash());
            map.put("ctx", setting.getWebUrl());

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstant.SUCCESS);
            instance.setData(map);

            return instance;

        } catch (Exception e) {
            logger.error("api v3 driver completeTask error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstant.SERVER_ERROR);
        }

    }

    @RequestMapping(value = "completeTask2")
    public @ResponseBody
    String completeTask2(
        HttpServletResponse response,
        Long driverId, Long orderId, Long couponId, Double discount,
        BigDecimal couponMoney, BigDecimal cashMoney, BigDecimal signMoney, BigDecimal balanceMoney,
        PayType payType, PayTypeDetails payTypeDetails,
        Double shouldCash, Double realCash, Double mileage, String carNumber,
        Integer waitedTime, Long waitStartTime, Long travelBeginTime) {

        response.setCharacterEncoding("utf-8");

        logger.debug("recv driverId:{},orderId:{},couponId:{},discount:{},"
                + "couponMoney:{},cashMoney:{},signMoney:{},balanceMoney:{},"
                + "payType:{},payTypeDetails:{},"
                + "shouldCash:{},realCash:{},mileage:{},carNumber:{},"
                + "waitedTime:{},waitStartTime:{},travelBeginTime:{}",
            driverId, orderId, couponId, discount, couponMoney, cashMoney, signMoney, balanceMoney,
            payType, payTypeDetails, shouldCash, realCash, mileage, carNumber,
            waitedTime, waitStartTime, travelBeginTime);

        if (null == driverId || null == orderId || null == payType || null == payTypeDetails ||
            null == shouldCash || null == realCash || null == mileage ||
            null == waitedTime || null == waitStartTime || null == travelBeginTime) {
            return "callback({code:" + ErrorConstant.PARAM_ERROR.getMessage() + "})";
        }

        try {

            Driver driver = driverService.findOne(driverId);

            if (null == driver) {
                return "callback({code:" + ErrorConstant.DRIVER_NOT_EXISTS.getMessage() + "})";
            }

            Order order = orderService.findOne(orderId);
            if (null == order) {
                return "callback({code:" + ErrorConstant.ORDER_NOT_EXISTS_ERROR.getMessage() + "})";
            }

            if (!order.getStatus().equals(Order.ORDER_STATUS_BUSY)) {
                return "callback({code:" + ErrorConstant.ORDER_STATUS_ERROR.getMessage() + "})";
            }

            if (!order.getDriverId().equals(driverId)) {
                return "callback({code:" + ErrorConstant.ORDER_DRIVER_OWNER_ERROR.getMessage()
                    + "})";
            }

            if (null != couponId) {
                Coupon coupon = couponService.findOne(couponId);
                if (null != coupon) {
                    if (!coupon.getStatus().equals(Coupon.COUPON_STATUS_NOTUSE)) {
                        return "callback({code:" + ErrorConstant.COUPON_INVALID.getMessage() + "})";
                    }
                }
            }

            order.setDiscount(discount);
            order.setCouponMoney(couponMoney);
            order.setCashMoney(cashMoney);
            order.setSignMoney(signMoney);
            order.setBalanceMoney(balanceMoney);

            order.setShouldCash(new BigDecimal(shouldCash));
            order.setRealCash(new BigDecimal(realCash));
            order.setFinishTime(new Date());
            order.setStatus(Order.ORDER_STATUS_FINISHED);

            BigDecimal m = new BigDecimal(mileage);
            double df = m.setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue();
            order.setMileage(df);

            order.setWaitedTime(waitedTime);
            order.setTravelTime(
                (int) ((order.getFinishTime().getTime() - travelBeginTime) / (1000 * 60)));
            order.setPayType(payType);
            order.setPayTypeDetails(payTypeDetails);
            order.setCarNumber(carNumber);

            orderService.completeTaskV3(order, new Date(waitStartTime), new Date(travelBeginTime),
                couponId);

            //完成工单事件
            Passenger passenger = memberService.findOnePassengerByPhone(order.getClientPhone());
            ReactorVo rVo = new ReactorVo();
            rVo.setDriver(driver);
            rVo.setOrder(order);

            OrderFinishEvent finishEvent = new OrderFinishEvent(rVo);
            applicationEventMulticaster.multicastEvent(finishEvent);

            if (null != passenger) {
                ReactorVo rVo2 = new ReactorVo();
                rVo2.setOrder(order);
                rVo2.setPassenger(passenger);
                rVo2.setActivityEvent(ActivityEvent.orderCompleteTimes);
                ActivityCheckEvent activityCheckEvent = new ActivityCheckEvent(rVo2);
                applicationEventMulticaster.multicastEvent(activityCheckEvent);

                MemberRebateEvent memberRebateEvent = new MemberRebateEvent(passenger, order,
                    order.getRealCash(), 1);
                applicationEventMulticaster.multicastEvent(memberRebateEvent);
            }

            return "callback({code:" + ErrorConstant.SUCCESS.getCode() + "})";

        } catch (Exception e) {
            logger.error("api v3 driver completeTask2 error: {}", e);
            return "callback({code:" + ErrorConstant.SERVER_ERROR.getMessage() + "})";
        }

    }

    /**
     * 推荐人二维码
     */
    @RequestMapping("getQrCode")
    public @ResponseBody
    ResultTransport getQrCode(HttpServletRequest req, Long id, String appKey, String token,
        String timestamp) {

        logger.debug("recv id:{},appKey:{},token:{},timestamp:{}", id, appKey, token, timestamp);

        if (null == id || SecurityUtils.isBlank(appKey, token, timestamp)) {
            return ResultTransport.getErrorBy(ErrorConstant.PARAM_ERROR);
        }

        List<String> params = new LinkedList<String>();
        params.add(String.valueOf(id));
        params.add(timestamp);
        params.add(appKey);

        if (!SecurityUtils.checkToken(params, token)) {
            return ResultTransport.getErrorBy(ErrorConstant.TOKEN_ERROR);
        }

        String bathPath = getBasePath(req);

        Company company = null;
        String qrLogo = null;
        File logof = null;
        Driver driver = driverService.findOne(id);

        Setting setting = settingUtils.get();

        String shareUrl = defaultDriverRebateService.getWeixinShareCodeUrl(driver);

        if (null != driver) {
            company = companyService.findOne(driver.getCompanyId());
        }
        if (null != company) {
            qrLogo = company.getLogo();
        }
        if (null != qrLogo) {
            logof = new File(bathPath, qrLogo);
        }

        String srcLogo = null;

        if (null != logof && logof.exists()) {
            srcLogo = logof.getAbsolutePath();
        }

        SimpleDateFormat monthFormat = new SimpleDateFormat("yyyyMM");
        Date now = new Date();
        String monthstr = monthFormat.format(now);
        String filestr = "qrcode/driver/" + monthstr + "/" + now.getTime() + ".jpg";

        File f = new File(bathPath, filestr);
        if (!f.getParentFile().exists()) {
            f.getParentFile().mkdirs();
        }

        QRCodeUtil.encode(shareUrl, 500, 500, srcLogo, bathPath + "/" + filestr);

        ResultTransport instance = ResultTransport.getErrorBy(ErrorConstant.SUCCESS);

        Map<String, Object> dataMap = new HashMap<String, Object>();
        dataMap.put("picture", setting.getWebUrl() + "/" + filestr);
        if (null != company) {
            DriverRebate driverRebate = driverRebateService.findByDriverId(id);
            dataMap.put("shareTitle", company.getIntroduceTitle2());
            dataMap.put("shareContent", company.getIntroduceContent2());
            if (null != driverRebate) {
                dataMap.put("showContent", driverRebate.getContent());
            } else {
                dataMap.put("showContent", "");
            }
        } else {
            dataMap.put("shareTitle", "");
            dataMap.put("shareContent", "");
            dataMap.put("showContent", "");
        }

        instance.setData(dataMap);
        return instance;

    }

//    @RequestMapping("shareQrCode/{id}")
//    public String shareQrCode(HttpServletRequest req, Model model, @PathVariable("id") Long id) {
//
//        Driver driver = driverService.findOne(id);
//        model.addAttribute("driver", driver);
//        model.addAttribute("wxsetting", settingUtils.getWx());
//        model.addAttribute("company", companyService.findOne(driver.getCompanyId()));
//
//        return "driverrebate/shareqrcode";
//
//    }

    @RequestMapping("smsQrCode")
    public @ResponseBody
    Result<PhoneSmsRecord> smsQrCode(String phone, Long driverIntroducerId) {
        System.out.println("smsQrCode:" + phone);
        Result<PhoneSmsRecord> result = new Result<PhoneSmsRecord>();

        Driver driverIntroducer = driverService.findOne(driverIntroducerId);
        Company introducerCompany = companyService.findOne(driverIntroducer.getCompanyId());
        Company finalCompany = introducerCompany;
        Company main = companyService.getMain();
        Setting setting = settingUtils.get();
        if (!main.getId().equals(introducerCompany.getId()) && setting.isSmsMainCompany()) {
            finalCompany = main;
        }
        PhoneSmsRecord phoneSmsRecord = phoneSmsRecordService.findByPhone(phone);
        if (null != phoneSmsRecord) {
            long time = (System.currentTimeMillis() - phoneSmsRecord.getExpired().getTime()) / 1000;//多少秒
            if (time < 120) {//2分内禁止发送
                result.setErrorcode("0");
                result.setObject(120 - time);
                return result;
            } else if (time >= 120 && time < 30 * 60) {//30分内发送旧的
                result.setErrorcode("1");
                int code = -99;
                try {
//                    String con = "尊敬的用户您好,验证码：" + phoneSmsRecord.getVcode();
                    SmsTemplet templet = smsService
                        .findByAlias(finalCompany.getId(), SmsType.customDriver);
//                    if (templet == null) {
//                        SmsTemplet smsTemplet = new SmsTemplet();
//                        smsTemplet.setSmsType(SmsType.customDriver);
//                        smsTemplet.setCompanyId(finalCompany.getId());
//                        smsTemplet.setContent("{content}");
//                        smsService.insertSmsTemplate("给服务人员发自定义短信", SmsTemplet.SMSTEMPLATE_TYPE_CODE, smsTemplet);
//                    }
                    if (templet != null && StringUtils.isNotBlank(templet.getContent())) {
                        //code = smsService.sendSms(phone, "customDriver", "{\"content\":\"" + con + "\"}", finalCompany.getId(), 2, finalCompany.getSignName());
                        //短信发送（改）
                        JSONObject smsParam = new JSONObject();
                        smsParam.put("code", phoneSmsRecord.getVcode());
                        code = smsService
                            .sendSms(phone, templet.getTemplateId(), smsParam.toJSONString(),
                                finalCompany.getId(), 2, finalCompany.getSignName());
                    }
                } catch (Exception e) {
                }
                logger.debug("验证码发送结果：" + code + "，验证码：" + phoneSmsRecord.getVcode());
                if (code == 0) {
                    result.setSuccess(true);
                    phoneSmsRecord.setExpired(new Date());
                    phoneSmsRecordService.update(phoneSmsRecord);
                }
                return result;
            } else {//超过30分 发送新的
                result.setErrorcode("1");
                String newCode = String.valueOf(RandomString.randomNum(4));
                int code = -99;
                try {
//                    String con = "尊敬的用户您好,验证码：" + newCode;
                    SmsTemplet templet = smsService
                        .findByAlias(finalCompany.getId(), SmsType.customDriver);
//                    if (templet == null) {
//                        SmsTemplet smsTemplet = new SmsTemplet();
//                        smsTemplet.setSmsType(SmsType.customDriver);
//                        smsTemplet.setCompanyId(finalCompany.getId());
//                        smsTemplet.setContent("{content}");
//                        smsService.insertSmsTemplate("给服务人员发自定义短信", SmsTemplet.SMSTEMPLATE_TYPE_CODE, smsTemplet);
//                    }
                    if (templet != null && StringUtils.isNotBlank(templet.getContent())) {
                        //code = smsService.sendSms(phone, "customDriver", "{\"content\":\"" + con + "\"}", finalCompany.getId(), 2, finalCompany.getSignName());
                        //短信发送（改）
                        JSONObject smsParam = new JSONObject();
                        smsParam.put("code", newCode);
                        code = smsService
                            .sendSms(phone, templet.getTemplateId(), smsParam.toJSONString(),
                                finalCompany.getId(), 2, finalCompany.getSignName());
                    }
                } catch (Exception e) {
                }
                logger.debug("验证码发送结果：" + code + "，验证码：" + newCode);
                if (code == 0) {
                    result.setSuccess(true);
                    phoneSmsRecord.setExpired(new Date());
                    phoneSmsRecord.setVcode(newCode);
                    phoneSmsRecordService.update(phoneSmsRecord);
                }
                return result;
            }
        } else {
            String newCode = String.valueOf(RandomString.randomNum(4));
            int code = -99;
            try {
                String con = "尊敬的用户您好,验证码：" + newCode;
                SmsTemplet templet = smsService
                    .findByAlias(finalCompany.getId(), SmsType.customDriver);
//                if (templet == null) {
//                    SmsTemplet smsTemplet = new SmsTemplet();
//                    smsTemplet.setSmsType(SmsType.customDriver);
//                    smsTemplet.setCompanyId(finalCompany.getId());
//                    smsTemplet.setContent("{content}");
//                    smsService.insertSmsTemplate("给服务人员发自定义短信", SmsTemplet.SMSTEMPLATE_TYPE_CODE, smsTemplet);
//                }
                if (templet != null && StringUtils.isNotBlank(templet.getContent())) {
//                    code = smsService.sendSms(phone, "customDriver", "{\"content\":\"" + con + "\"}", finalCompany.getId(), 2, finalCompany.getSignName());
                    //短信发送（改）
                    JSONObject smsParam = new JSONObject();
                    smsParam.put("code", newCode);
                    code = smsService
                        .sendSms(phone, templet.getTemplateId(), smsParam.toJSONString(),
                            finalCompany.getId(), 2, finalCompany.getSignName());
                }
            } catch (Exception e
            ) {
                e.printStackTrace();
            }
            logger.debug("验证码发送结果：" + code + "，验证码：" + newCode);
            if (code == 0) {
                result.setSuccess(true);
                phoneSmsRecord = new PhoneSmsRecord();
                phoneSmsRecord.setCompanyId(finalCompany.getId());
                phoneSmsRecord.setExpired(new Date());
                phoneSmsRecord.setPhone(phone);
                phoneSmsRecord.setVcode(newCode);
                phoneSmsRecordService.save(phoneSmsRecord);
            }
            return result;
        }

    }

    //####down
    @RequestMapping(value = "downloadShareQrCode", method = RequestMethod.POST)
    public @ResponseBody
    Result<MemberRebate> downloadShareQrCode(String phone, String code, Long id) {

        logger.debug("recv phone:{},code:{},id:{}", phone, code, id);

        Result<MemberRebate> vo = new Result<MemberRebate>();
        vo.setSuccess(false);

        if (StringUtils.isBlank(phone) || StringUtils.isBlank(code) || null == id) {
            vo.setMessage("参数错误");
            return vo;
        }

        PhoneSmsRecord phoneSmsRecord = phoneSmsRecordService.findByPhone(phone);
        if (null == phoneSmsRecord || !phoneSmsRecord.getVcode().equals(code)) {
            vo.setMessage("验证码错误");
            return vo;
        }

        Driver driverIntroducer = driverService.findOne(id);
        Passenger passenger = memberService.findOnePassengerByPhone(phone);

        boolean firstIntroducer = false;//第一次

        if (null == passenger) {
            passenger = new Passenger();
            passenger.setPhone(phone);
            passenger.setType(Passenger.TYPE_PASSENGER);
            passenger.setChannel_name(Passenger.PASSENGER_CHANNEL_INVITE);
            passenger.setAllowOverdraw(Boolean.FALSE);
            if (null != driverIntroducer) {
                Company company = companyService.findOne(driverIntroducer.getCompanyId());
                passenger.setCompanyId(company.getId());
                passenger.setCompanyName(company.getAbbreviation());
                passenger.setIntroducer(driverIntroducer.getUsername());
                passenger.setIntroduceType(1);

                firstIntroducer = true;
            } else {
                Company company = companyService.getMain();
                passenger.setCompanyId(company.getId());
                passenger.setCompanyName(company.getAbbreviation());
            }
            Result<Passenger> result = memberService.createPersonal(passenger);

            if (result.isSuccess()) {
                //新注册活动f
                ReactorVo rVo = new ReactorVo();
                rVo.setPassenger(result.getResult());
                rVo.setActivityEvent(ActivityEvent.newRegister);
                ActivityCheckEvent activityCheckEvent = new ActivityCheckEvent(rVo);
                applicationEventMulticaster.multicastEvent(activityCheckEvent);

                if (firstIntroducer) {
                    MemberRebateEvent memberRebateEvent = new MemberRebateEvent(result.getResult(),
                        null, null, 0);
                    applicationEventMulticaster.multicastEvent(memberRebateEvent);
                }
            } else {
                vo.setMessage(result.getMessage());
                return vo;
            }

        }

        phoneSmsRecordService.deleteByPhone(phone);

        Map<String, Object> urlMap = new HashMap<String, Object>();
//        AppVersion androidcustomer = appVersionService.findByAppVersionType(AppVersion.AppVersionType.androidcustomer);
//        AppVersion ioscustomer = appVersionService.findByAppVersionType(AppVersion.AppVersionType.ioscustomer);
        Setting setting = settingUtils.get();
        urlMap.put("androidUrl", setting.getAndroidCustomer());
//        urlMap.put("iosUrl", setting.getIosCustomer());

        vo.setMap(urlMap);
        vo.setSuccess(true);

        return vo;

    }

    @RequestMapping("appXiazai")
    public String appXiazai(HttpServletRequest req, Model model) {

        return "driverrebate/appxiazai";

    }

    @RequestMapping(value = "queryMembers", method = RequestMethod.POST)
    public @ResponseBody
    ResultTransport queryMembers(Long driverId, Integer page, Integer limit, String appKey,
        String token, String timestamp) {
        logger.debug(" driverId:{},appKey:{},token:{},timestamp:{},page:{},limit:{}", driverId,
            appKey, token, timestamp, page, limit);

        if (driverId == null || SecurityUtils.isBlank(appKey, token, timestamp)) {
            return ResultTransport.getErrorBy(ErrorConstant.PARAM_ERROR);
        }

        List<String> params = new LinkedList<String>();
        params.add(String.valueOf(driverId));
        params.add(String.valueOf(page));
        params.add(String.valueOf(limit));
        params.add(timestamp);
        params.add(appKey);

        if (!SecurityUtils.checkToken(params, token)) {
            return ResultTransport.getErrorBy(ErrorConstant.TOKEN_ERROR);
        }

        try {
            Driver driver = driverService.findOne(driverId);
            String username = null;
            if (null != driver) {
                username = driver.getUsername();
            }
            Page<Map<String, Object>> memberPage = memberService
                .queryByIntroducer(username, Passenger.INTRODUCE_TYPE_DRIVER, page, limit);
            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstant.SUCCESS);
            instance.setData(memberPage);

            return instance;

        } catch (Exception e) {
            logger.error("api v3 member pageNotice error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstant.SERVER_ERROR);
        }

    }

    @RequestMapping(value = "queryRebate", method = RequestMethod.POST)
    public @ResponseBody
    ResultTransport queryRebate(Long driverId, Integer page, Integer limit, String appKey,
        String token, String timestamp) {
        logger.debug(" driverId:{},appKey:{},token:{},timestamp:{},page:{},limit:{}", driverId,
            appKey, token, timestamp, page, limit);

        if (driverId == null || SecurityUtils.isBlank(appKey, token, timestamp)) {
            return ResultTransport.getErrorBy(ErrorConstant.PARAM_ERROR);
        }

        List<String> params = new LinkedList<String>();
        params.add(String.valueOf(driverId));
        params.add(String.valueOf(page));
        params.add(String.valueOf(limit));
        params.add(timestamp);
        params.add(appKey);

        if (!SecurityUtils.checkToken(params, token)) {
            return ResultTransport.getErrorBy(ErrorConstant.TOKEN_ERROR);
        }

        try {

            Page<DriverPaymentsRecord> rebatePage = driverPaymentsRecordService
                .queryByEmploy(driverId, DriverPaymentsRecord.RECHARGE_TYPE_REBATE, null, null,
                    null, page, limit);

            List<DriverPaymentsRecord> content = rebatePage.getContent();
            long totalElements = rebatePage.getTotalElements();

            List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
            if (!CollectionUtils.isEmpty(content)) {
                for (DriverPaymentsRecord driverPaymentsRecord : content) {
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("date", driverPaymentsRecord.getHappend());
                    map.put("memo", driverPaymentsRecord.getMemo());
                    map.put("money", driverPaymentsRecord.getMoney());
                    mapList.add(map);
                }
            }
            Pageable pageable = new PageRequest(page, limit);
            Page<Map<String, Object>> pageMap = new PageImpl<Map<String, Object>>(mapList, pageable,
                totalElements);

            BigDecimal totalMoney = driverPaymentsRecordService
                .sumRebateByEmployWithDate(driverId, null, null);

            Map<String, Object> dataMap = new HashMap<String, Object>();
            dataMap.put("page", pageMap);
            dataMap.put("totalMoney", totalMoney);

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstant.SUCCESS);
            instance.setData(dataMap);

            return instance;

        } catch (Exception e) {
            logger.error("api v3 member pageNotice error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstant.SERVER_ERROR);
        }

    }

    private String getBasePath(HttpServletRequest req) {

        try {
            return WebUtils.getRealPath(req.getSession().getServletContext(), "/");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        return StringUtils.EMPTY;
    }


}
